package controllers

import (
	"github.com/astaxie/beego"
	"image"
	"bytes"
	"image/png"
	"image/jpeg"
	"Pandaria/librarys/errorCode"
	"github.com/fogleman/gg"
	"github.com/astaxie/beego/logs"
)

type BaseController struct {
	beego.Controller
}

func (this *BaseController) Options() {
	this.Data["json"] = map[string]interface{}{"status": 0, "message": "ok"}
	this.ServeJSON()
}

func (this *BaseController) OutPut(data string, message string) {
	this.Data["json"] = map[string]interface{}{"success": 1, "message": message, "data": data}
	this.ServeJSON(true)
}

func (this *BaseController) OutPutErrMsg(message string) {
	this.Data["json"] = map[string]interface{}{"success": -1, "message": message}
	this.ServeJSON(true)
}

func (this *BaseController) OutPutError(err error) {
	this.Data["json"] = map[string]interface{}{"success": -1, "message": err.Error()}
	this.ServeJSON(true)
}

func (this *BaseController) OutputImg(img image.Image, imgType string) {
	emptyBuff := bytes.NewBuffer(nil)
	switch imgType {
	default:
		this.Ctx.ResponseWriter.Header().Set("Content-Type", "image/jpeg")
		jpeg.Encode(emptyBuff, img, nil)
	case "png":
		this.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
		png.Encode(emptyBuff, img)

	}

	sendBytes := emptyBuff.Bytes()
	this.Ctx.ResponseWriter.Write([]byte(sendBytes))
}

func (this *BaseController) OutputImgNotFound(msg string) {
	emptyBuff := bytes.NewBuffer(nil)
	img, err := gg.LoadImage("static/img/404.png")
	if err != nil {
		logs.Error(err)
	}
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
	this.Ctx.ResponseWriter.Header().Set("Err-No", errorCode.IMG_NOTFOUND)
	this.Ctx.ResponseWriter.Header().Set("Err-Msg", msg)
	png.Encode(emptyBuff, img)
	sendBytes := emptyBuff.Bytes()
	this.Ctx.ResponseWriter.Write([]byte(sendBytes))
}
